package com.zjpavt.client.extenddevice.serial;

import com.zjpavt.client.enums.ExtendDeviceEnum;
import com.zjpavt.client.extenddevice.AbstractExtendDevice;
import com.zjpavt.client.extenddevice.IExtendDevice;
import com.zjpavt.client.nativemethod.JnIMethod;

/**
 * 串口一转十外设 桐庐控制激光灯电源
 *
 * @author zyc
 */
public class SerialPortModule extends AbstractExtendDevice implements IExtendDevice {
    public static final String TURN_ON = "MOP";
    public static final String TURN_OFF = "MCL";
    public static final String CHECK_BACK_COMMAND = "<AT_DECADE0_OK>";
    public static final String ALL_LOWER_NUM = "10";
    public static final String ALL_LOWER_NUM_ORDER = "0d";

    private int channelNum;
    private int lowerComputerNum;

    /**
     * 串口一转十外设 桐庐控制激光灯电源
     * @param extendNum
     * */
    public SerialPortModule(int extendNum) {
        super(extendNum, ExtendDeviceEnum.SERIAL_TRANSFORM);
    }

    public void openAll() {
        for (int i = 1; i <= 10; i++) {
            openAllLowerByChanenelNum(i);
        }
    }

    public void openAllLowerByChanenelNum(int channelNum) {
        String channelString = "0" + Integer.toString(channelNum, 16);
        sendCommand(channelString,ALL_LOWER_NUM,true);
    }
    public void open(int channelNum, int lowerComputerNum) {
        String channelString = "0" + Integer.toString(channelNum, 16);
        String lowerComputerString = "0" + Integer.toString(channelNum, 16);
        sendCommand(channelString,lowerComputerString,true);
    }

    public void closeAll() {
        for (int i = 1; i <= 10; i++) {
            closeAllLowerByChanenelNum(i);
        }
    }


    public void closeAllLowerByChanenelNum(int channelNum) {
        String channelString = "0" + Integer.toString(channelNum, 16);
        sendCommand(channelString,ALL_LOWER_NUM,false);

    }
    public void close(int channelNum, int lowerComputerNum) {
        String channelString = "0" + Integer.toString(channelNum, 16);
        String lowerComputerString = "0" + Integer.toString(channelNum, 16);
        sendCommand(channelString,lowerComputerString,false);
    }

    private void sendCommand(String channelNum, String lowerComputer, boolean isOn) {
        String command;
        if (isOn) {
            command = "<AT_T" + channelNum + "_W" + lowerComputer + "_" + TURN_ON + ">";
        } else {
            command = "<AT_T" + channelNum + "_W" + lowerComputer + "_" + TURN_OFF + ">";
        }
        JnIMethod.sendMessage2ExtendDeviceByRs485Safe(115200,getExtendNum(),command,200);
    }
}
